import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { lokiService } from '../services/loki-service'

// 定义日志查询参数接口
interface LogQueryParams {
  namespace: string
  pod: string
  startTime: string
  endTime: string
  keyword: string
}

// 定义日志存储
export const useLogStore = defineStore('log', () => {
  // 状态
  const logs = ref<string[]>([])
  const isLoading = ref(false)
  const isLiveMode = ref(false)
  const error = ref<string | null>(null)
  const queryParams = ref<LogQueryParams>({
    namespace: '',
    pod: '',
    startTime: '',
    endTime: '',
    keyword: ''
  })

  // 计算属性
  const hasLogs = computed(() => logs.value.length > 0)
  const logCount = computed(() => logs.value.length)

  // 方法
  const fetchLogs = async () => {
    if (!queryParams.value.namespace || !queryParams.value.pod) {
      error.value = '请选择命名空间和Pod'
      return
    }

    try {
      isLoading.value = true
      error.value = null
      logs.value = await lokiService.queryLogs(queryParams.value)
    } catch (err) {
      error.value = '查询日志失败'
      console.error(err)
    } finally {
      isLoading.value = false
    }
  }

  const clearLogs = () => {
    logs.value = []
  }

  const setLiveMode = (value: boolean) => {
    isLiveMode.value = value
  }

  const updateQueryParams = (params: Partial<LogQueryParams>) => {
    queryParams.value = { ...queryParams.value, ...params }
  }

  return {
    logs,
    isLoading,
    isLiveMode,
    error,
    queryParams,
    hasLogs,
    logCount,
    fetchLogs,
    clearLogs,
    setLiveMode,
    updateQueryParams
  }
})